<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #canvas {
            border: 1px solid black;
            background-color: whitesmoke;
        }
    </style>
</head>
<body>
画笔颜色：
<input type="color" id="colors"/>

画笔粗细：
<select id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<button id="clear">清除</button>

<br/>
<br/>
<canvas width="600px" height="400px" id="canvas"></canvas>
<script>
    const cvs = document.querySelector("#canvas")
    const ctx = cvs.getContext('2d')


    // 鼠标左键是否被按下
    let status = false

    // 画笔颜色
    let color = "#000"

    // 画笔粗细
    let lineWidth = 1

    // 获取用户选择的颜色
    document.querySelector('#colors').addEventListener('change', e => {
        color = e.target.value
    })

    // 获取画笔粗细
    document.querySelector('#select').onchange = function (e) {
        console.log(e)
        lineWidth = e.target.value
    }

    // 鼠标点击事件
    cvs.addEventListener('mousedown', (e) => {

        console.log(e)
        status = true
        const {offsetX, offsetY} = e
        ctx.strokeStyle = color
        ctx.lineWidth = lineWidth
        ctx.beginPath()
        ctx.moveTo(offsetX, offsetY)
    })

    // 鼠标经过事件
    cvs.addEventListener('mousemove', (e) => {

        //  鼠标左键被按下时
        if (status) {
            const {offsetX, offsetY} = e
            ctx.lineTo(offsetX, offsetY)
            ctx.strokeStyle = color
            ctx.lineWidth = lineWidth
            ctx.stroke()
        }
    })

    // 鼠标抬起
    cvs.addEventListener('mouseup', () => {
        status = false
    })

    // 清除画布
    document.querySelector('#clear').addEventListener('click', () => {
        cvs.width = 600
        cvs.height = 400
    })
</script>
</body>
</html>